package server.business.service.Impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcelFactory;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.toolkit.LambdaUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import server.business.mapper.OverallBloodMapper;
import server.business.mapper.PatientTransfusionInformationMapper;
import server.business.pojo.PatientTransfusionInformation;
import server.business.service.PatientTransfusionInformationService;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Galaxy
 * @description 针对表【patient_transfusion_information(患者输血信息表)】的数据库操作Service实现
 * @createDate 2022-11-08 12:46:24
 */
@Service("patientTransfusionInformationService")
public class PatientTransfusionInformationServiceImpl extends ServiceImpl<PatientTransfusionInformationMapper, PatientTransfusionInformation>
        implements PatientTransfusionInformationService {

    /**
     * 处理sql查询字段名 拼接wrapper和lambdawrapper查询项
     * @param columns
     * @SFunction PatientTransfusionInformation
     * @return
     */
    private String getParamSql(SFunction<PatientTransfusionInformation, ?>... columns) {
        return Arrays.stream(columns).map(c -> StrUtil.toUnderlineCase(LambdaUtils.getName(c))).collect(Collectors.joining(StringPool.COMMA, StringPool.SPACE, StringPool.SPACE));
    }

    /**
     *
     * @param patientId
     * @description 获取需要支付的总金额
     * @return 个人信息列表
     */
    @Override
    public List<Map<String, Object>> listPayPrice(String patientId) {
        QueryWrapper<PatientTransfusionInformation> listPaywrapper =new QueryWrapper<>();
        listPaywrapper
                .lambda()
                .eq(PatientTransfusionInformation::getState,0)
                .eq(PatientTransfusionInformation::getPatientId,patientId);
        listPaywrapper
                .select("IFNULL(sum(pay_money),0)  as totalMoney");
        List<Map<String, Object>> maps = this.listMaps(listPaywrapper);
        System.out.println(maps.getClass().toString());
        return maps;
    }
    /**
     *
     * @param patientId,payState
     * @description 获取输血费用明细
     * @return 输血明细费用列表（包含/不包含已支付订单）
     */
    @Override
    public List<PatientTransfusionInformation> listPayAlonePrice(String payState, String patientId) {
        QueryWrapper<PatientTransfusionInformation> listPaywrapper = new QueryWrapper<>();
        listPaywrapper
                .lambda()
                .eq(PatientTransfusionInformation::getPatientId,patientId);
        //        筛选订单
        if(payState.equals("1")) {
            listPaywrapper
                    .lambda()
                    .eq(PatientTransfusionInformation::getState, "0");
        }
        List<PatientTransfusionInformation> list = this.list(listPaywrapper);
        System.out.println(list);
        return list;
    }
    /**
     *
     * @param bloodId
     * @description 通过血液ID搜索输血记录
     * @return 输血记录
     */
    @Override
    public List<PatientTransfusionInformation> getBloodRecoredById(String bloodId) {
        QueryWrapper<PatientTransfusionInformation> wrapper = new QueryWrapper<>();
        wrapper
                .lambda()
                .eq(PatientTransfusionInformation::getBloodId,bloodId);
        List<PatientTransfusionInformation> list = this.list(wrapper);
        return list;
    }
    /**
     *
     * @param patientId,startTime,endTime
     * @description 患者用血信息查询报告
     * @return 患者用血详情
     */
    @Override
    public List<PatientTransfusionInformation> getPersonBloodInfo(String patientId, Timestamp startTime, Timestamp endTime) {

        QueryWrapper<PatientTransfusionInformation> wrapper = new QueryWrapper<>();
        wrapper.select("sum(blood_count) as blood_count",
                        getParamSql(PatientTransfusionInformation::getDepartment),
                        getParamSql(PatientTransfusionInformation::getName),
                        getParamSql(PatientTransfusionInformation::getPatientId),
                        getParamSql(PatientTransfusionInformation::getAboBloodType),
                        getParamSql( PatientTransfusionInformation::getRhBloodType),
                        getParamSql(PatientTransfusionInformation::getBloodType))
                .lambda()
                .eq(PatientTransfusionInformation::getPatientId,patientId)
                .between(PatientTransfusionInformation::getCreateTime,startTime,endTime)
                .groupBy(PatientTransfusionInformation::getAboBloodType,
                        PatientTransfusionInformation::getRhBloodType,
                        PatientTransfusionInformation::getBloodType,
                        PatientTransfusionInformation::getDepartment,
                        PatientTransfusionInformation::getName);
        List<PatientTransfusionInformation> list = this.list(wrapper);
        return list;
    }
    /**
     *
     * @param department,startTime,endTime
     * @description 科室用血信息查询报告
     * @return 科室用血详情
     */
    @Override
    public List<PatientTransfusionInformation> getDepartBloodInfo(String department, Timestamp startTime, Timestamp endTime) {

        QueryWrapper<PatientTransfusionInformation> wrapper = new QueryWrapper<>();
        System.out.println(department);
        wrapper.select("sum(blood_count) as blood_count",
                        getParamSql(PatientTransfusionInformation::getDepartment),
                        getParamSql(PatientTransfusionInformation::getAboBloodType),
                        getParamSql(PatientTransfusionInformation::getRhBloodType),
                        getParamSql(PatientTransfusionInformation::getBloodType))
                .lambda()
                .eq(PatientTransfusionInformation::getDepartment,department)
                .between(PatientTransfusionInformation::getCreateTime,startTime,endTime)
                .groupBy(
                        PatientTransfusionInformation::getAboBloodType,
                        PatientTransfusionInformation::getRhBloodType,
                        PatientTransfusionInformation::getBloodType);
        List<PatientTransfusionInformation> list = this.list(wrapper);
        System.out.println(list);
        return list;
    }


    @Override
    public HashMap<String, Object> getGO(String bloodId) {
        LambdaQueryWrapper<PatientTransfusionInformation> wrapper =new LambdaQueryWrapper<>();
        wrapper.eq(PatientTransfusionInformation::getBloodId,bloodId)
                .select(PatientTransfusionInformation::getName,PatientTransfusionInformation::getDepartment,PatientTransfusionInformation::getPatientId);
        HashMap<String,Object> map = (HashMap<String, Object>) this.listMaps(wrapper).get(0);
        System.out.println(map);
        return map;
    }


    //*************************************zy*************************start

    // 装配数据库查询
    @Autowired
    private PatientTransfusionInformationMapper patientTransfusionInformationMapper;

    /**
     * 根据患者id和输血单号查询所有输血信息
     *
     * @param patientId         患者Id
     * @param transfusionNumber 输血单号
     * @return 返回当前患者的输血信息列表
     */
    @Override
    public PatientTransfusionInformation findAllTransfusionByPatientIdAndTransfusionNumber(String patientId, String transfusionNumber) {
        LambdaQueryWrapper<PatientTransfusionInformation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(patientId != null, PatientTransfusionInformation::getPatientId, patientId)
                .eq(Strings.isNotBlank(transfusionNumber), PatientTransfusionInformation::getTransfusionNumber, transfusionNumber);
        return patientTransfusionInformationMapper.selectOne(queryWrapper);
    }

    /**
     * 根据患者退血申请单号在患者输血信息表中查询血液Id
     *
     * @param transfusionNumber 患者输血申请单号
     * @return 返回血液Id
     */
    @Override
    public String findBloodIdByTransfusionNumber(String transfusionNumber) {
        return patientTransfusionInformationMapper.findBloodIdByTransfusionNumber(transfusionNumber);
    }

    /**
     * 根据输血单号修改血液状态
     *
     * @param transfusionNumber 输血单号
     * @param state             血液状态
     */
    @Override
    public void setStateByTransfusionNumber(String transfusionNumber, String state) {
        patientTransfusionInformationMapper.setStateByTransfusionNumber(transfusionNumber, state);
    }

    @Autowired
    private OverallBloodMapper overallBloodMapper;

    /**
     * 分页查询功能
     *
     * @param currentPage                       当前页面
     * @param pageSize                          页面显示个数
     * @param patientTransfusionInformationList 患者输血信息
     * @return 返回分页查询结果
     */
    @Override
    public IPage<PatientTransfusionInformation> getPage(int currentPage, int pageSize, List<PatientTransfusionInformation> patientTransfusionInformationList) {
        LambdaQueryWrapper<PatientTransfusionInformation> queryWrapper = new LambdaQueryWrapper<>();
        List<Long> ids = new ArrayList<>();
        for (PatientTransfusionInformation patientTransfusionInformation : patientTransfusionInformationList) {
            try {
                ids.add(patientTransfusionInformation.getId());
            } catch (Exception e) {
                System.out.println("没有您想查询的数据！");
            }
        }
        queryWrapper.in(ids.size() != 0, PatientTransfusionInformation::getId, ids);
        Page<PatientTransfusionInformation> page = new Page<>(currentPage, pageSize);
        patientTransfusionInformationMapper.selectPage(page, queryWrapper);
        return page;
    }

    /**
     * 根据编号批量下载选中数据
     *
     * @param response 请求
     * @param ids      编号列表
     */
    @Override
    public void batchDownload(HttpServletResponse response, ArrayList<Long> ids) throws IOException {
        List<PatientTransfusionInformation> patientTransfusionInformations = patientTransfusionInformationMapper.selectBatchIds(ids);
        // 设置文本内容
        try {
            response.setContentType("application/vnd.ms-excel");
            String fileName = URLEncoder.encode("患者退血申请信息" + System.currentTimeMillis(), "UTF-8");
            // 设置字符编码
            response.setCharacterEncoding("utf-8");
            // 设置响应头
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcelFactory.write(response.getOutputStream(),
                    PatientTransfusionInformation.class).sheet("患者退血申请信息")
                    .doWrite(patientTransfusionInformations);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //*************************************zy*************************end


}




